﻿// -----------------------------------------------------------------------
// <copyright file="AuthorizeEdit.ascx.cs" company="VDC" author="ltduc" >
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace VDC.VONE.WEB.Modules.Authorize.Controls
{
    using System;
    using System.Globalization;
    using System.Reflection;
    using System.Web;
    using System.Web.UI.WebControls;
    using AdCom.Utility;
    using VDC.COMMON;
    using VDC.COMMON.ExceptionHelpers;
    using VDC.VONE.BLL;
    using VDC.VONE.ENTITIES;

    /// <summary>
    /// Class AuthorizeEdit
    /// </summary>
    public partial class AuthorizeEdit : System.Web.UI.UserControl
    {
        #region Constants
        /// <summary>
        /// Url AuthorizeList
        /// </summary>
        private const string UrlBack = "AuthorizeList.aspx?PageIndex={0}";

        /// <summary>
        /// The name
        /// </summary>
        private const string Name = "FullName";

        /// <summary>
        /// The user authorizeId
        /// </summary>
        private const string UserId = "UserId";

        /// <summary>
        /// The CHONNGUOIDUNG
        /// </summary>
        private const string CHONNGUOIDUNG = "--Chọn người được ủy quyền--";

        /// <summary>
        /// Const DEFAULTUSERDEPARTMENT
        /// </summary>
        private const string DEFAULTUSERDEPARTMENT = "--Chọn phòng ban, vị trí--";

        /// <summary>
        /// Const Format UserDepartment Name: "{0}, {1}"
        /// </summary>
        private const string FORMATUSERDEPARTMENTNAME = "{0}, {1}";

        /// <summary>
        /// Const Select
        /// </summary>
        private const string SELECT = "Select$";

        /// <summary>
        /// Const KEY
        /// </summary>
        private const string KEY = "KEY";

        /// <summary>
        /// AuthorizesId for Authorize
        /// </summary>
        private readonly int authorizeId = HtmlHelper.GetIntFromRequestString(Constants.Id, -1);

        /// <summary>
        /// Index trang
        /// </summary>
        private readonly int pageIndex = HtmlHelper.GetIntFromRequestString(Constants.PageIndex, 0);
        #endregion
        #region Methods
        /// <summary>
        /// Event Page Load
        /// </summary>
        /// <param name="sender">Param Page</param>
        /// <param name="e">Param e</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            string methodName = MethodBase.GetCurrentMethod().DeclaringType.ToString() + Constants.Dot + MethodBase.GetCurrentMethod().Name;
            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);
            try
            {
                if (!this.IsPostBack)
                {
                    this.Page.DataBind();
                    var user = new UserEN();
                    var userService = new UserService();
                    user = userService.GetUserByUserName(this.Page.User.Identity.Name);
                    this.BindaAuthorizeBeenUser();
                    this.BindataddlAuthorize();
                    this.LoadData();
                    LogHelper.Instance.WriteInfo(Constants.End + methodName);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError(methodName + Constants.Colon + ex.ToString());
                ExceptionHandler.Instance.HandleUiException(ex);
            }
        }

        /// <summary>
        /// Event Save Authorize
        /// </summary>
        /// <param name="sender">Param sender</param>
        /// <param name="e">Param e</param>
        protected void Save_Click(object sender, EventArgs e)
        {
            string methodName = MethodBase.GetCurrentMethod().DeclaringType.ToString() + Constants.Dot + MethodBase.GetCurrentMethod().Name;
            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);
            try
            {
                if (this.Validate())
                {
                    this.Save();
                    this.Back();
                }

                LogHelper.Instance.WriteLog(HttpContext.Current.User.Identity.Name, methodName, false);
                LogHelper.Instance.WriteInfo(Constants.End + methodName);
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError(methodName + Constants.Colon + ex.ToString());
                ExceptionHandler.Instance.HandleUiException(ex);
            }
        }

        /// <summary>
        /// Event SaveAndNew
        /// </summary>
        /// <param name="sender">Param sender</param>
        /// <param name="e">Param e</param>
        protected void SaveAndNew_Click(object sender, EventArgs e)
        {
            string methodName = MethodBase.GetCurrentMethod().DeclaringType.ToString() + Constants.Dot + MethodBase.GetCurrentMethod().Name;
            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);
            try
            {
                if (this.Validate())
                {
                    this.SaveAndNew();
                }

                LogHelper.Instance.WriteLog(HttpContext.Current.User.Identity.Name, methodName, false);
                LogHelper.Instance.WriteInfo(Constants.End + methodName);
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError(methodName + Constants.Colon + ex.ToString());
                ExceptionHandler.Instance.HandleUiException(ex);
            }
        }

        /// <summary>
        /// Event Cancel
        /// </summary>
        /// <param name="sender">Param sender</param>
        /// <param name="e">Param e</param>
        protected void Cancel_Click(object sender, EventArgs e)
        {
            string methodName = MethodBase.GetCurrentMethod().DeclaringType.ToString() + Constants.Dot + MethodBase.GetCurrentMethod().Name;
            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);
            try
            {
                this.ResetData();
                LogHelper.Instance.WriteInfo(Constants.End + methodName);
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError(methodName + Constants.Colon + ex.ToString());
                ExceptionHandler.Instance.HandleUiException(ex);
            }
        }

        /// <summary>
        /// Event Delete
        /// </summary>
        /// <param name="sender">Param sender</param>
        /// <param name="e">Param e</param>
        protected void Delete_Click(object sender, EventArgs e)
        {
            string methodName = MethodBase.GetCurrentMethod().DeclaringType.ToString() + Constants.Dot + MethodBase.GetCurrentMethod().Name;
            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);
            try
            {
                this.Delete();
                this.Back();
                LogHelper.Instance.WriteLog(HttpContext.Current.User.Identity.Name, methodName, false);
                LogHelper.Instance.WriteInfo(Constants.End + methodName);
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError(methodName + Constants.Colon + ex.ToString());
                ExceptionHandler.Instance.HandleUiException(ex);
            }
        }

        /// <summary>
        /// Event Back
        /// </summary>
        /// <param name="sender">Param sender</param>
        /// <param name="e">Param e</param>
        protected void Back_Click(object sender, EventArgs e)
        {
            string methodName = MethodBase.GetCurrentMethod().DeclaringType.ToString() + Constants.Dot + MethodBase.GetCurrentMethod().Name;
            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);
            try
            {
                this.Back();
                HttpContext.Current.ApplicationInstance.CompleteRequest();
                LogHelper.Instance.WriteInfo(Constants.End + methodName);
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError(methodName + Constants.Colon + ex.ToString());
                ExceptionHandler.Instance.HandleUiException(ex);
            }
        }

        /// <summary>
        /// Eveent GrdView_OnSelectedIndexChanged
        /// </summary>
        /// <param name="sender">Param sender</param>
        /// <param name="e">Param e</param>
        protected void GrdView_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            string methodName = MethodBase.GetCurrentMethod().DeclaringType.ToString() + Constants.Dot + MethodBase.GetCurrentMethod().Name;
            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);
            try
            {
                if (this.grdView.SelectedValue != null)
                {
                    var userDepartmentId = Convert.ToInt32(this.grdView.SelectedValue);
                    var userDepartmentService = new UserDepartmentService();
                    var userDepartment = userDepartmentService.GetUserDepartmentById(userDepartmentId);

                    if (userDepartment != null && userDepartment.Department != null && userDepartment.Position != null)
                    {
                        this.txtUserDepartment.Text = string.Format(FORMATUSERDEPARTMENTNAME, userDepartment.Department.Name, userDepartment.Position.Name);
                        this.txtUserDepartmentHidden.Text = this.txtUserDepartment.Text;
                        this.SetKey(userDepartmentId);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError(methodName + Constants.Colon + ex.ToString());
                ExceptionHandler.Instance.HandleUiException(ex);
            }
        }

        /// <summary>
        /// Event GrdView_RowDataBound
        /// </summary>
        /// <param name="sender">param sender</param>
        /// <param name="e">param e</param>
        protected void GrdView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes[Constants.ClientEvent.Click] = this.Page.ClientScript.GetPostBackClientHyperlink(this.grdView, SELECT + e.Row.RowIndex);
            }
        }

        /// <summary>
        /// Validate for Save, SaveAndNew
        /// </summary>
        /// <returns>Return Validate?</returns>
        private bool Validate()
        {
            bool isValid = true;
            this.lbError.Text = string.Empty;

            var authorizeService = new AuthorizeService();
            var authorizeBeenUserId = -1;
            var startDate = DateTime.MinValue;
            var endDate = DateTime.MinValue;

            if (!string.IsNullOrEmpty(this.ddlAuthorizeBeenUser.SelectedValue))
            {
                authorizeBeenUserId = Convert.ToInt32(this.ddlAuthorizeBeenUser.SelectedValue);
            }

            if (!string.IsNullOrEmpty(this.txtStartDate.Text))
            {
                startDate = DateTime.ParseExact(this.txtStartDate.Text, Constants.DateTimeDisplay, CultureInfo.CurrentUICulture);
            }

            if (!string.IsNullOrEmpty(this.txtEndDate.Text))
            {
                endDate = DateTime.ParseExact(this.txtEndDate.Text, Constants.DateTimeDisplay, CultureInfo.CurrentUICulture);
            }

            if (authorizeService.Exist(this.authorizeId, authorizeBeenUserId, startDate, endDate))
            {
                this.lbError.Text += string.Format(PublicFuncs.GetMessage(Messages.MessageAuthorizeExist), PublicFuncs.HtmlEncode(this.ddlAuthorizeBeenUser.SelectedItem.Text));
                isValid = false;
            }

            return isValid;
        }

        /// <summary>
        /// Method LoadData
        /// </summary>
        private void LoadData()
        {
            var authorizeService = new AuthorizeService();

            if (this.authorizeId != -1)
            {
                var authorize = authorizeService.GetAuthorizeById(this.authorizeId);
                if (authorize.AuthorizeUserId > 0)
                {
                    this.txtAuthorizeUser.Text = authorize.AuthorizeUser.FullName;
                }

                if (authorize.AuthorizeBeenUserId > 0)
                {
                    this.ddlAuthorizeBeenUser.SelectedValue = Convert.ToString(authorize.AuthorizeBeenUserId);
                }

                if (authorize.Department != null && authorize.Position != null)
                {
                    this.txtUserDepartment.Text = string.Format(FORMATUSERDEPARTMENTNAME, authorize.Department.Name, authorize.Position.Name);
                    this.txtUserDepartmentHidden.Text = this.txtUserDepartment.Text;
                    var userDepartmentService = new UserDepartmentService();
                    var userDepartment = userDepartmentService.GetUserDepartmentByUserDepartmentPosition(authorize.AuthorizeUserId, authorize.DepartmentId, authorize.PositionId);
                    if (userDepartment != null)
                    {
                        this.grdView.SelectedIndex = this.GetSelectedIndex(userDepartment.UserDepartmentId);
                    }
                }

                this.txtStartDate.Text = authorize.StartDate.HasValue ? authorize.StartDate.Value.ToString(Constants.DateTimeDisplay) : string.Empty;
                this.txtEndDate.Text = authorize.EndDate.HasValue ? authorize.EndDate.Value.ToString(Constants.DateTimeDisplay) : string.Empty;

                this.btnDelete.Visible = true;
                this.btnSaveAndNew.Visible = false;
                this.lblHeader.Text = PublicFuncs.GetMessage(Messages.HeaderUpdateAuthorize);
            }
            else
            {
                var userService = new UserService();
                var user = userService.GetUserByUserName(this.Page.User.Identity.Name);

                this.txtAuthorizeUser.Text = user.FullName;
                this.ddlAuthorizeBeenUser.Text = string.Empty;
                this.txtUserDepartment.Text = DEFAULTUSERDEPARTMENT;
                this.txtEndDate.Text = string.Empty;
                this.txtStartDate.Text = DateTime.Now.ToString(Constants.DateTimeDisplay);

                this.btnDelete.Visible = false;
                this.btnSaveAndNew.Visible = true;
                this.lbError.Text = string.Empty;
                this.lblHeader.Text = PublicFuncs.GetMessage(Messages.HeaderAddAuthorize);
            }
        }

        /// <summary>
        /// Method ResetData
        /// </summary>
        private void ResetData()
        {
            if (this.authorizeId != -1)
            {
                var authorizeService = new AuthorizeService();
                var authorize = authorizeService.GetAuthorizeById(this.authorizeId);
                if (authorize.AuthorizeUserId > 0)
                {
                    this.txtAuthorizeUser.Text = authorize.AuthorizeUser.FullName;
                }

                if (authorize.AuthorizeBeenUserId > 0)
                {
                    this.ddlAuthorizeBeenUser.SelectedValue = Convert.ToString(authorize.AuthorizeBeenUserId);
                }

                if (authorize.Department != null && authorize.Position != null)
                {
                    this.txtUserDepartment.Text = string.Format(FORMATUSERDEPARTMENTNAME, authorize.Department.Name, authorize.Position.Name);
                    this.txtUserDepartmentHidden.Text = this.txtUserDepartment.Text;
                    var userDepartmentService = new UserDepartmentService();
                    var userDepartment = userDepartmentService.GetUserDepartmentByUserDepartmentPosition(authorize.AuthorizeUserId, authorize.DepartmentId, authorize.PositionId);
                    if (userDepartment != null)
                    {
                        this.grdView.SelectedIndex = this.GetSelectedIndex(userDepartment.UserDepartmentId);
                    }
                }

                this.txtStartDate.Text = authorize.StartDate.HasValue ? authorize.StartDate.Value.ToString(Constants.DateTimeDisplay) : string.Empty;
                this.txtEndDate.Text = authorize.EndDate.HasValue ? authorize.EndDate.Value.ToString(Constants.DateTimeDisplay) : string.Empty;
            }
            else
            {
                this.ddlAuthorizeBeenUser.Text = string.Empty;
                this.txtUserDepartment.Text = string.Empty;
                this.grdView.SelectedIndex = -1;
                this.txtEndDate.Text = string.Empty;
                this.txtStartDate.Text = DateTime.Now.ToString(Constants.DateTimeDisplay);
            }
        }

        /// <summary>
        /// Method Save
        /// </summary>
        private void Save()
        {
            var authorizeService = new AuthorizeService();
            var authorize = new AuthorizeEN();
            authorize.AuthorizeId = this.authorizeId;
            if (this.authorizeId != -1)
            {
                authorize = authorizeService.GetAuthorizeById(this.authorizeId);

                if (!string.IsNullOrEmpty(this.ddlAuthorizeBeenUser.SelectedValue))
                {
                    authorize.AuthorizeBeenUserId = Convert.ToInt32(this.ddlAuthorizeBeenUser.SelectedValue);
                }

                var userDepartmentId = this.GetKey();
                if (userDepartmentId != null)
                {
                    var userDepartmentService = new UserDepartmentService();
                    var userDepartment = userDepartmentService.GetUserDepartmentById(Convert.ToInt32(userDepartmentId));
                    authorize.DepartmentId = userDepartment.DepartmentId;
                    authorize.PositionId = userDepartment.PositionsId;
                }

                if (!string.IsNullOrEmpty(this.txtStartDate.Text))
                {
                    authorize.StartDate = DateTime.ParseExact(this.txtStartDate.Text, Constants.DateTimeDisplay, CultureInfo.CurrentUICulture);
                }

                if (!string.IsNullOrEmpty(this.txtEndDate.Text))
                {
                    authorize.EndDate = DateTime.ParseExact(this.txtEndDate.Text, Constants.DateTimeDisplay, CultureInfo.CurrentUICulture);
                }

                authorize.Date = DateTime.Now;
                authorizeService.Update(authorize);
                this.lbError.Text = PublicFuncs.GetMessage(Messages.MessageEditAuthorizeSuccess);
            }
            else
            {
                var userService = new UserService();
                var user = userService.GetUserByUserName(this.Page.User.Identity.Name);
                authorize.AuthorizeUserId = user.UserId;

                if (!string.IsNullOrEmpty(this.ddlAuthorizeBeenUser.SelectedValue))
                {
                    authorize.AuthorizeBeenUserId = Convert.ToInt32(this.ddlAuthorizeBeenUser.SelectedValue);
                }

                var userDepartmentId = this.GetKey();
                if (userDepartmentId != null)
                {
                    var userDepartmentService = new UserDepartmentService();
                    var userDepartment = userDepartmentService.GetUserDepartmentById(Convert.ToInt32(userDepartmentId));
                    authorize.DepartmentId = userDepartment.DepartmentId;
                    authorize.PositionId = userDepartment.PositionsId;
                }

                if (!string.IsNullOrEmpty(this.txtStartDate.Text))
                {
                    authorize.StartDate = DateTime.ParseExact(this.txtStartDate.Text, Constants.DateTimeDisplay, CultureInfo.CurrentUICulture);
                }

                if (!string.IsNullOrEmpty(this.txtEndDate.Text))
                {
                    authorize.EndDate = DateTime.ParseExact(this.txtEndDate.Text, Constants.DateTimeDisplay, CultureInfo.CurrentUICulture);
                }

                authorize.Date = DateTime.Now;

                authorizeService.Insert(authorize);
                this.lbError.Text = PublicFuncs.GetMessage(Messages.MessageAddAuthorizeSuccess);
            }
        }

        /// <summary>
        /// Bindataddls the authorize been user.
        /// </summary>
        private void BindaAuthorizeBeenUser()
        {
            var user = new UserEN();
            var userService = new UserService();
            user = userService.GetUserByUserName(this.Page.User.Identity.Name);
            var lstNodeType = userService.GetAllUserByUserId(user.UserId);
            this.ddlAuthorizeBeenUser.DataTextField = Name;
            this.ddlAuthorizeBeenUser.DataValueField = UserId;
            this.ddlAuthorizeBeenUser.DataSource = lstNodeType;
            this.ddlAuthorizeBeenUser.DataBind();
            this.ddlAuthorizeBeenUser.Items.Insert(0, new ListItem(CHONNGUOIDUNG, string.Empty));
        }

        /// <summary>
        /// Bindataddls the authorize.
        /// </summary>
        private void BindataddlAuthorize()
        {
            var userService = new UserService();
            var currentUser = userService.GetUserByUserName(this.Page.User.Identity.Name);
            this.grdView.DataSource = currentUser.UserDepartments;
            this.grdView.DataBind();
        }

        /// <summary>
        /// Method SaveAndNew
        /// </summary>
        private void SaveAndNew()
        {
            this.Save();
            this.ResetData();
        }

        /// <summary>
        /// Method Delete
        /// </summary>
        private void Delete()
        {
            var authorizeService = new AuthorizeService();
            authorizeService.Delete(this.authorizeId);
        }

        /// <summary>
        /// Method Back
        /// </summary>
        private void Back()
        {
            this.Response.Redirect(string.Format(UrlBack, this.pageIndex), false);
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }

        /// <summary>
        /// Set Key For UserDepartment
        /// </summary>
        /// <param name="value">param value</param>
        private void SetKey(object value)
        {
            this.txtUserDepartment.Attributes[KEY] = Convert.ToString(value);
        }

        /// <summary>
        /// Get Key For UserDepartment
        /// </summary>
        /// <returns>return object</returns>
        private object GetKey()
        {
            return this.txtUserDepartment.Attributes[KEY];
        }

        /// <summary>
        /// Get SelectedIndex For GridView
        /// </summary>
        /// <param name="userDepartmentId">param userDepartmentId</param>
        /// <returns>return index</returns>
        private int GetSelectedIndex(object userDepartmentId)
        {
            for (int i = 0; i < this.grdView.DataKeys.Count; i++)
            {
                var dataKey = this.grdView.DataKeys[i];
                if (dataKey != null && dataKey.Value.Equals(userDepartmentId))
                {
                    return i;
                }
            }

            return -1;
        }
        #endregion
    }
}